import { exportExcelAxio } from '@tapui/api/office'
import { mixin_base } from '@tapui/mixins/mixin_base'
export const mixin_multiheader_excel = {
  mixins: [mixin_base],
  /** 组件数据 */
  data() {
    return {}
  },
  /** 计算 */
  computed: {},
  /** 组件方法 */
  methods: {
    /** 导出Excel*/
    doExportExcelWithHeader() {
      if (!this.beforeExportData()) return
      let cols = this.getColumnsTree()
      // let url = baseUrl + `${this.url.exportExcel}`
      let url = `${this.url.exportExcelMergeHeader}`
      let data = {}
      Object.assign(data, this.getQueryParams(), { cols: cols })
      exportExcelAxio({ url: url, data: data })
        .then(res => {
          var reader = new FileReader()
          reader.readAsText(res.data, 'utf-8')
          reader.onload = () => {
            try {
              var info = JSON.parse(reader.result)
              this.$tap.alert(info.message)
            } catch (e) {
              var isTaskExport = res.headers.istaskexport
              if (isTaskExport === '1') {
                this.$tap.alert('系统正在导出，请到excel导出任务页面下载')
              } else {
                var blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8' })
                var filename = decodeURI(res.headers['filename'])
                if (typeof filename === 'undefined') {
                  filename = '导出数据.xlsx'
                }
                var tempObjectUrl = window.URL.createObjectURL(blob)
                var aLink = document.createElement('a')
                aLink.style.display = 'none'
                aLink.download = filename
                aLink.href = tempObjectUrl
                document.body.appendChild(aLink)
                aLink.click()
                document.body.removeChild(aLink)
                window.URL.revokeObjectURL(tempObjectUrl)
                this.afterExportData()
              }
            }
          }
        })
        .catch(error => {
          this.$tap.alert(error, 'warning')
        })
    },
    // 以嵌套数组形式 获取所有行
    getColumnsTree() {
      let cols = []
      let colcomp = this.$refs.mainTable.$children.filter(comp => comp.$options._componentTag === 'el-table-column')
      colcomp.forEach(col => {
        let subcol = this.getColumnsTreeRecursive(col)
        cols.push(subcol)
      })
      return cols
    },
    // 递归获取子列
    getColumnsTreeRecursive(col) {
      if (col.$children.length > 0) {
        let subcols = new Array(0)
        col.$children.forEach(col => {
          subcols.push(this.getColumnsTreeRecursive(col))
        })
        return { subcols: subcols, prop: col.$options.propsData.prop, label: col.$options.propsData.label }
      } else {
        return { subcols: [], prop: col.$options.propsData.prop, label: col.$options.propsData.label }
      }
    }
  }
}

